import {isEmpty,encrypt,judgeExpireTimestamp,UniAsync,DeBounce} from './index'
import {authCheck,forwardLogin} from './page'
// 目前没有针对uni的Fly版本，使用wx版本没有问题
var Fly=require("flyio/dist/npm/wx")
//var fly=new Fly
var tokenFly = new Fly

//fly.config.headers={'X-Requested-With':'XMLHttpRequest'}
//tokenFly.config.headers={'X-Requested-With':'XMLHttpRequest'}

import application from '@/settings/Application'

let {appid,secret,domain,routeState,http,network,lineType} = application;
//fly.config.baseURL= domain;
tokenFly.config.baseURL= domain;


export default class HttpClient{
  constructor(auth=true,showLoading=true){
    this.flyclient = new Fly;
    this.flyclient.config.baseURL= domain;
    this.flyclient.config.timeout=http.timeout;
    this.flyclient.config.headers={
      //'Content-Type':'application/json',
      "lineType":lineType}
    //设置拦截
    this.authProcess(auth,showLoading);
  }

  authProcess(auth=true,showLoading=true){
    //if(!auth) return;
    let $this = this;
    //添加请求拦截器
    this.flyclient.interceptors.request.use(
      async (request,promise)=>{
      $this.request = request;
	  //console.log("request:",request)
	  const value = uni.getStorageSync('previewLoading');
	  if(showLoading&&!value){
		  uni.showLoading({
		    title: '加载中',
		    mask:true
		  });
	  }
      
    //request.headers['lineType']= lineType;
    //request.headers['Content-Type']= 'application/json';


      // #ifdef APP-PLUS
      if(network.networkType==undefined){
        const res =  await UniAsync((resolve)=>{
          uni.getNetworkType({
            success: function (res) {
                resolve(res);
            }
        });
        });
        const {networkType} = res;
        network.networkType = networkType;
      }
      if(network.networkType=='none') {
        uni.hideLoading();
        const message = '网络不通或连接没有打开！';
        uni.showToast({
          title: message,
          duration: 2000,
          icon:'none'
      });
        return promise.resolve({
          success:false,
          message:message
        });
      }
      // #endif
	  // request.headers['lineType'] = lineType;
      if(!auth) return request;
        const callbackSuccess = ({token})=>{
          request.headers['X-Access-Token']= token;
        }

        const exceptionCallback = ()=>{
          if (!routeState.navigateToLogin){
            uni.navigateTo({
              url: '/pages/system/login/index',
              success:function(){
                routeState.navigateToLogin = true;
              }
            })
          }
        }

        //uni.hideLoading();
        authCheck({exceptionCallback,callbackSuccess});
        if(routeState.navigateToLogin){
          uni.hideLoading();
          return promise.resolve({
            success:false,
            message:'请求不合法，终止请求'
          });
        }

        return request;
    })
    //添加响应拦截器，响应拦截器会在then/catch处理之前执行
    this.flyclient.interceptors.response.use(
      async (response, promise) => {
	  const value = uni.getStorageSync('previewLoading');
	  if(showLoading&&!value){
		  uni.hideLoading();
	  }
		uni.setStorageSync('failTimes',0);
        
        let resultDto = response.data;
         // if(!auth) return promise.resolve(resultDto);
		 //50013:无此账号，50003：session filter异常
        if(!resultDto.success&&resultDto.code!=50003){
          console.log('toast')
          if(resultDto.message!=null){
              uni.showToast({
                  title: resultDto.message,  //标题
                  icon: 'none',  //图标，支持"success"、"loading"
              });
          }
          // 50002
          if([50001,50003,50010,50007,50011,50012].find(s=>s==resultDto.code)!=undefined){
            /* 每周一的情况 */
            uni.removeStorage({key:'tokenInfo'});
            uni.removeStorage({key:'keepLoginData'});
            setTimeout(() => {
              forwardLogin();
            }, 500);
          }
          else if (resultDto.code == 5000){
            uni.removeStorage({key:'tokenInfo'});
            //uni.removeStorageSync('X-Access-Token')
            //let Wcode = await WxLogin();
            let keepLoginData = uni.getStorageSync('keepLoginData');
            if (!isEmpty(keepLoginData)){
              uni.showLoading({
                title: '令牌重置中',
                //mask:true
              })
              let resp = await tokenFly.post(
                //'/api/ClientLogin/customerLogin',
                '/api/user/customerLogin',
                  //'ce9850b6-a9a1-471b-a436-817f025b5ae5',
                keepLoginData
              );
              let resultDto_ = resp.data;
              if(resultDto_.success){
                let tokenInfo = {token:resultDto_.result.token,timestamp:new Date().getTime()};
                let {method,baseURL,url,headers,body} = {...$this.request};
                headers['X-Access-Token']= tokenInfo.token;
                const resultDto__ = await tokenFly.request(url, body, {method,headers});
                uni.setStorage(
                  {
                    key:'tokenInfo',
                    data:tokenInfo
                  }
                );
                uni.hideLoading();
                routeState.navigateToLogin = false;
                return promise.resolve(resultDto__.data);
              }else {
                setTimeout(() => {
                  forwardLogin();
                }, 500);
              }
              uni.hideLoading();
            }
            else {
              setTimeout(() => {
                forwardLogin();
              }, 500);
            }
          }
        }
        return promise.resolve(resultDto)
      },
      (err, promise) => {
        console.log('err.message:',err.message)
		let failTimes = uni.getStorageSync('failTimes');
		failTimes = isEmpty(failTimes)?1:parseInt(failTimes)+1;
		if(failTimes>=5){
			console.log('网络请求大于5次，');
			uni.$emit('failTooMany');
			uni.redirectTo({
				url: '/pages/error'
			});
			uni.setStorageSync('failTimes',0);
		}else{
			uni.setStorageSync('failTimes',failTimes);
		}
        uni.hideLoading()
        uni.showToast({
          title: '网络异常',
          icon: 'none'
        })
        return promise.resolve({success:false,message:'网络异常'})
      }
    )
  }
}


